<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use app\model\SubjectRecord;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'), '/');
        }

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 3600*24*2;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
            Cookie::delete('oauth_login');
        });
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $lanmu_tips = '';
        if(empty($user->birthday) || empty($user->mobile)){

        }else if($user->avatar == '/assets/img/avatar.png'){
            $lanmu_tips = __("user_self_face");
        }
        $this->view->assign('lanmu_tips',$lanmu_tips);
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password', '', null);
            $email = $this->request->post('email','');
            $mobile = $this->request->post('mobile','');
            $is_email = config('global.is_email');

            if($is_email){
                $check_email = filter_var( $username,FILTER_VALIDATE_EMAIL);
                if(empty($check_email)) {
                    //邮箱不合法
                    $this->error("Email is Error");
                }
                $email = $username;
            }else{
                $mobile = $username;
            }

            $has_read_service_put = $this->request->post('has_read_service_put','');
            $has_read_public_put = $this->request->post('has_read_public_put','');
            if(empty($has_read_service_put)){
                $this->error(__('please_read'));
            }
            if(empty($has_read_public_put)){
                $this->error(__('please_read2'));
            }

            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
//                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
//                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            $captchaType = 'mobile';
            if($is_email){
                $captchaType = 'email';
            }
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
                } elseif ($captchaType == 'email') {
                    $captchaResult = Ems::check($email, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        $this->view->assign('is_email', config('global.is_email'));
        $this->assignconfig('is_email',  config('global.is_email'));

        $articleData = db('article')->find(2);
        $articleData2 = db('article')->find(3);
        $articleData = $this->formateDataBylang($articleData,['title','descript'],false);
        $articleData2 = $this->formateDataBylang($articleData2,['title','descript'],false);
        $this->view->assign('articleData', $articleData);
        $this->view->assign('articleData2', $articleData2);
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ?: url('user/index'));
        }
        if ($this->request->isPost()) {

            $account = $this->request->post('account');
            $password = $this->request->post('password', '', null);
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
//                '__token__' => 'require|token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $articleData = db('article')->find(2);
        $articleData = $this->formateDataBylang($articleData,['title','descript'],false);
        $this->view->assign('url', $url);
        $this->view->assign('articleData', $articleData);
        $this->view->assign('title', __('Login'));
        $this->view->assign('is_email', config('global.is_email'));
        $this->assignconfig('is_email',  config('global.is_email'));
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $this->token();
            //退出本站
            Cookie::delete('oauth_login');
            $this->auth->logout();
            $this->success(__('Logout successful'), url('index/index'),'',2);
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        $this->view->assign('start_time', date("Y-m-d"));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword", '', null);
            $newpassword = $this->request->post("newpassword", '', null);
            $renewpassword = $this->request->post("renewpassword", '', null);
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|regex:\S{6,30}',
                'newpassword'   => 'require|regex:\S{6,30}',
                'renewpassword' => 'require|regex:\S{6,30}|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
                'renewpassword.confirm' => __('Password and confirm password don\'t match')
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    public function attachment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $where = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['mimetype']) && preg_match("/(\/|\,|\*)/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = array_filter(explode(',', $filterArr['mimetype']));
                    foreach ($mimetypeArr as $index => $item) {
                        $query->whereOr('mimetype', 'like', '%' . str_replace("/*", "/", $item) . '%');
                    }
                };
            } elseif (isset($filterArr['mimetype'])) {
                $where['mimetype'] = ['like', '%' . $filterArr['mimetype'] . '%'];
            }

            if (isset($filterArr['filename'])) {
                $where['filename'] = ['like', '%' . $filterArr['filename'] . '%'];
            }

            if (isset($filterArr['createtime'])) {
                $timeArr = explode(' - ', $filterArr['createtime']);
                $where['createtime'] = ['between', [strtotime($timeArr[0]), strtotime($timeArr[1])]];
            }
            $search = $this->request->get('search');
            if ($search) {
                $where['filename'] = ['like', '%' . $search . '%'];
            }

            $model = new Attachment();
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $total = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->count();

            $list = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->limit($offset, $limit)
                ->select();
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $mimetype = $this->request->get('mimetype', '');
        $mimetype = substr($mimetype, -1) === '/' ? $mimetype . '*' : $mimetype;
        $this->view->assign('mimetype', $mimetype);
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
        return $this->view->fetch();
    }

    public function bookings(){
        $user = $this->auth->getUser();
        $subjectRecordModel = new SubjectRecord();
        $dataArr = $subjectRecordModel->with(['teacher','subject'])->where("user_id",$user->id)->order("id desc")->limit(30)->select();

        if($this->lanagecode == 'en'){
            $weekArr = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
        }else{
            $weekArr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
        }

        $configdata = db('config')->where('group','basic')->where("can_set",1)->select();
        $sysData = [];
        foreach ($configdata as $item){
            $sysData[$item['name']] = $item['value'];
        }
        foreach ($dataArr as &$data){

            $teacher = $data['teacher'];
            $subject = $data['subject'];
            $teacher=$this->formateDataBylang($teacher,['name','descript'],false);
            $subject=$this->formateDataBylang($subject,['name','descript'],false);
            if(empty($teacher)){
                $teacher['name'] = '-';
            }
            $data['teacher'] = $teacher;
            $data['subject'] = $subject;
            $jiaoshi = db('room')->where('id',$data['jiaoshi_id'])->find();
            $jiaoshi=$this->formateDataBylang($jiaoshi,['name'],false);
            $data['jiaoshi_name'] = $jiaoshi['name'];

            $data['team_teacher'] = '';
            if(!empty($data['team_teacher_id'])){
                $teamTeacherName = db('admin')->where('id',$data['team_teacher_id'])->value('name_en');
                $data['team_teacher'] = ' , '.$teamTeacherName;
            }

            $data['can_cancle'] = 1;
            //是否在开始的前2个小时么
            //是否已開始上課了
            if(time() > $data['start_time']){
                $data['can_cancle'] = 0;
            } else if(!empty($sysData['yuyue_cancle_hour'])){
                $leftTime = time()- $data['start_time'];
                $leftHour = ($leftTime*-1)/3600;
                if($leftTime < 0 && $leftHour < $sysData['yuyue_cancle_hour']){
                    $data['can_cancle'] = 0;
                }
            }
            if($data['status'] < 0){
                $data['can_cancle'] = 0;
            }
            $weekDay = $weekArr[date("w",$data['start_time'])];
            if($this->lanagecode == 'en'){
                $data['today'] = date("M j",$data['start_time']);
            }else{
                $data['today'] = date("m-d",$data['start_time']);
            }

            $data['start_time'] = date("H:i",$data['start_time'])." ".date("A",$data['start_time']);
            $data['end_time'] = date("H:i",$data['end_time'])." ".date("A",$data['end_time']);
            $data['weekDay'] = $weekDay;
        }

        $shop_tips = '';
        if(!empty($sysData['yuyue_cancle_hour'])){
            $shop_tips = __('Cannot be cancelled %s hours before class',$sysData['yuyue_cancle_hour'],$this->lanagecode);
        }
        $this->view->assign('shop_tips',$shop_tips);
        $this->view->assign('recordData',$dataArr);
        $this->view->assign('title', __('Bookings'));
        return $this->view->fetch();
    }
    public function wallet(){
        $user = $this->auth->getUser();
        $where = [];
        $where['user_id'] = $user->id;
        $packageData = db('package_order')->where($where)->order("id desc")->limit(20)->select();

        $packageData = $this->formateDataBylang($packageData,['name']);
        foreach ($packageData as &$item){
            $packages = db('package')->where('id',$item['package_id'])->find();
            $packages = $this->formateDataBylang($packages,['name'],false);
            $item['package_name'] = $packages['name'];
            $item['price'] = round($item['price']);
            if($item['is_finish'] == 1){
                $item['left_time_num'] = 0;
                $item['can_time_num'] = 0;
            }else{
                //一共預約了多少次
                $total_record = db('subject_record')->where('package_order_id',$item['id'])->where('status','>=',1)->count();
                $total_record = intval($total_record);
                $item['can_time_num'] = $item['time_num'] - $total_record;
            }

            $kecheng_ids = explode(',',$item['kecheng_ids']);
            $subject_name = $subject_arr = [];
            $nums = count($kecheng_ids);
            foreach ($kecheng_ids as $kk => $s_id){
                if($kk>10){
//                    continue;
                }
                $subjectData = db('subject')->where('id',$s_id)->find();
                $subjectData = $this->formateDataBylang($subjectData,['name'],false);
                if(empty($subjectData) || $subjectData['is_delete'] == 1 || $subjectData['status'] == -1){
                    continue;
                }

                $subject_name[] = $subjectData['name'];

                $cateData = db('category')->where('id',$subjectData['cate_id'])->find();
                $cateData=$this->formateDataBylang($cateData,['name'],false);
                $subject_arr[] = ['name'=>$subjectData['name'],'long_time'=>$subjectData['long_time'],'cate_name'=>$cateData['name']];
            }
            /*if($nums>11){
                $subject_name[] = "...";
            }*/
            $item['subject_name'] = $subject_name;
            $item['subject_name_json'] = json_encode($subject_arr);
            $item['begin_time'] = date("Y-m-d",$item['begin_time']);
            $item['end_time'] = date("Y-m-d",$item['end_time']);
        }
        $this->view->assign('packageData',$packageData);
        $this->view->assign('wuxianzhi',__('wuxianzhi'));

        $this->view->assign('title', __('Wallet'));
        return $this->view->fetch();
    }
    public function language(){

        $this->view->assign('title', __('Language'));
        return $this->view->fetch();
    }
}
